<template>
    <div class="herb_list">
        <el-container>
            <el-header>
                <page-title>药材管理</page-title>
            </el-header>
            <el-main class="content">
                <div class="search_box">
                    <el-row :gutter="20" style="min-width:1024px">
                        <el-col :span="6">
                            药材名称：<el-input v-model="searchForm.name" style="width:50%"></el-input>
                        </el-col>
                        <el-col :span="6">
                            药材库存：<el-input v-model="searchForm.stock" style="width:50%"></el-input>
                        </el-col>
                        <el-col :span="6">
                            <el-button type="primary" @click="getData">查询结果</el-button>
                        </el-col>
                    </el-row>
                </div>

                <div class="add_btn">
                    <el-row :gutter="20" style="min-width:1024px">
                        <el-col :span="6"><div>&nbsp;</div></el-col>
                        <el-col :span="6"><div>&nbsp;</div></el-col>
                        <el-col :span="6"><div>&nbsp;</div></el-col>
                        <el-col :span="6" style="text-align:right">
                            <el-button plain @click="add">添加药材</el-button>
                        </el-col>
                    </el-row>
                </div>

                <div class="table_box">
                    <el-table
                        ref="table"
                        :data="tableData"
                        border
                        style="width: 100%"
                        @selection-change="selectAll">
                        <el-table-column
                            type="selection"
                            width="70">
                        </el-table-column>

                        <el-table-column
                            prop="name"
                            label="药材名称">
                        </el-table-column>

                        <el-table-column
                            label="药材图片"
                            width="120">
                            <template slot-scope="scope">
                                <img class="herb_img" :src="'http://renqing123.oss-cn-shenzhen.aliyuncs.com/'+scope.row.image">
                            </template>
                        </el-table-column>

                        <el-table-column
                            prop="stock"
                            label="库存">
                        </el-table-column>

                        <el-table-column
                            prop="company"
                            label="药材单位">
                        </el-table-column>

                        <el-table-column
                            prop="price"
                            label="价格（元）">
                        </el-table-column>

                        <el-table-column
                            prop="discount_price"
                            label="会员价格（元）">
                        </el-table-column>

                        <el-table-column
                            prop="explain"
                            label="药材使用说明"
                            min-width="200">
                        </el-table-column>

                        <el-table-column
                            label="操作"
                            align="center"
                            width="120">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
                                <el-button type="text" size="small" @click="del(id=[scope.row.id])">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination_box">
                        <div class="checkedAll">
                            <el-checkbox v-model="checkedAll" @change="isCheckedAll" style="margin-right:10px">全选</el-checkbox>
                            <el-button plain :disabled="isDelArr" @click="del(selectArr)">批量删除</el-button>
                        </div>
                        <el-pagination
                            layout="prev, pager, next"
                            :total="total"
                            :page-size = "pageSize"
                            @current-change="setCurrentPage">
                        </el-pagination>
                    </div>

                    <el-dialog
                        :title="title"
                        :visible.sync="boxSwitch"
                        width="670px"
                        :before-close="() => {boxSwitch = false}">
                        <el-form :model="form" :rules="rules" ref="herbForm">
                            <el-form-item label="药材名称：" label-width="160px" prop="name"  class="demo-ruleForm">
                                <el-input v-model="form.name" auto-complete="off" style="width:300px"></el-input>
                            </el-form-item>

                            <el-form-item label="药材图片：" label-width="160px">
                                <div style="display:flex">
                                    <!-- <img src="" style="width:100px;height:100px;margin-right:20px"> -->
                                    <update-img @clearImg="clearImg" @change="addImgEvent" :imgUrl="form.image"></update-img>
                                </div>
                            </el-form-item>
                            
                            <el-form-item label="库存数量：" label-width="160px" prop="stock">
                                <el-input v-model="form.stock" auto-complete="off" style="width:300px"></el-input>
                            </el-form-item>
                            <el-form-item label="药材单位：" label-width="160px" prop="company">
                                <el-input v-model="form.company" auto-complete="off" style="width:300px"></el-input>
                            </el-form-item>
                            <el-form-item label="药材价格：" label-width="160px" prop="price">
                                <el-input v-model="form.price" auto-complete="off" style="width:300px"></el-input>
                            </el-form-item>
                            <el-form-item label="会员价格：" label-width="160px" prop="discount_price">
                                <el-input v-model="form.discount_price" auto-complete="off" style="width:300px"></el-input>
                            </el-form-item>
                            <el-form-item label="药材使用说明：" label-width="160px">
                                <el-input
                                    type="textarea"
                                    :rows="2"
                                    placeholder="请输入内容"
                                    :autosize="{ minRows: 4, maxRows: 4}"
                                    style="width:300px"
                                    v-model="form.explain">
                                </el-input>
                            </el-form-item>
                        </el-form>
                        <span slot="footer" class="dialog-footer">
                            <el-button @click="boxSwitch = false">取 消</el-button>
                            <el-button type="primary" @click="submitWay" :loading="submitLoading">提 交</el-button>
                        </span>
                    </el-dialog>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script>
import * as api from './../../../api/api'
export default {
    data() {
        return{
            //------搜索相关-------
            searchForm: {
                name: '',
                stock: '',
            },
            //------表格相关-------
            tableData: [],//表格数据
            total: 0,//数据总条数
            offset: 0,//显示的页
            pageSize: 10,//每页显示条数
            selectArr: [],//选中的数据
            isDelArr: true,//禁用批量删除
            //------弹框相关------
            boxSwitch: false,//弹框开关
            title: '',//弹框标题
            submitLoading: false,//添加/编辑提交中
            checkedAll: false,//全选
            //弹框表单
            form: {
                name: '',
                image: '',
                stock: '',
                company: '',
                price: '',
                discount_price: '',
                explain: '',

            },
            //表单验证规则
            rules: {
                name: [
                    { required: true, message: '请输入药材名称', trigger: 'blur' }
                ],
                stock: [
                    { required: true, message: '请输入药材库存数量', trigger: 'blur' }
                ],
                company: [
                    { required: true, message: '请输入药材单位', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入药材价格', trigger: 'blur' }
                ],
                discount_price: [
                    { required: true, message: '请输入会员价格', trigger: 'blur' }
                ]
            },
            //上传图片相关
            imgBaseUrl: 'https://www.genxf.cn/base/upload-file',
            imgTitle: '上传图片'

        }
    },

    //计算属性
    computed: {

    },

    //钩子函数（页面挂载完成时触发）
    mounted() {
        this.getData();
    },

    //自定义方法
    methods: {
        //获取数据
        getData() {
            let body = {
                model: "Drugs",
                limit: this.pageSize,
                offset:this.offset,
                orderBy:"create_time desc",
                search: this.searchForm
            }
            api.getDateList(body).then(res=>{
                if(res.data.code==200){
                    this.tableData = res.data.data.data;
                    this.total = res.data.data.count * 1;
                }
            });
        },

        //分页
        setCurrentPage(currentPage) {
            this.offset = currentPage - 1;
            this.getData();
        },
        //全选
        selectAll(selection) {
            for (const item of selection) {
                this.selectArr.push(item.id)
            };
            if(selection.length === this.tableData.length){
                this.checkedAll = true;
            }else {
                this.checkedAll = false;
            };
            if(selection.length > 0){
                this.isDelArr = false;
            }else{
                this.isDelArr = true;
            }
        },
        isCheckedAll() {
            this.$refs.table.toggleAllSelection()
        },

        //提交任务指派
        submitWay() {
            //指派编辑提交
            if(this.title === '编辑药材'){
                this.editSubmit();
            }
            //指派添加提交
            else if(this.title === '添加药材'){
                this.addSubmit();
            }
        },

        //编辑--打开编辑框
        edit(row) {
            let data = row;
            this.title = "编辑药材";
            this.imgTitle = "重新上传"
            this.form.name = data.name;
            this.form.image = row.image;
            this.form.stock = row.stock;
            this.form.company = row.company;
            this.form.price = row.price;
            this.form.discount_price = row.discount_price;
            this.form.explain = row.explain;
            this.boxSwitch = true;
        },
        //编辑--提交编辑
        editSubmit() {
            let body = {
                model: "Drugs",
                data: this.form,
                update_condition: {
                    id: this.form.id * 1
                }
            };
            this.$refs.herbForm.validate((valid) => {
                if (valid) {
                    api.createData(body).then(res=>{
                        if(res.data.code === 200){
                            this.getData();
                            this.submitLoading = false;
                            this.boxSwitch = false;
                            this.$message({
                                message: '恭喜你，提交成功',
                                type: 'success'
                            });
                        }else {
                            this.$message.error(res.data.msg);
                            this.submitLoading = false;
                        }
                    });
                }
            });
        },

        //添加--打开添加框
        add() {
            this.title = "添加药材";
            this.imgTitle = "上传图片"
            this.form = {
                name: '',
                image: '',
                stock: '',
                company: '',
                price: '',
                discount_price: '',
                explain: '',
            };
            this.boxSwitch = true;
        },
        //添加--提交添加
        addSubmit() {
            let body = {
                model: "Drugs",
                data: this.form
            }
            let vm = this;
            this.$refs.herbForm.validate((valid) => {
                if (valid) {
                    api.createData(body).then(res=>{
                        if(res.data.code === 200){
                            if(res.data.code === 200){
                                vm.getData();
                                vm.submitLoading = false;
                                vm.boxSwitch = false;
                                vm.$message({
                                    message: '恭喜你，提交成功',
                                    type: 'success'
                                });
                            }else {
                                vm.$message.error(res.data.msg);
                                vm.submitLoading = false;
                            }
                        }
                    });
                }
            });
            
        },
        //删除
        del(id) {
            let body = {
                model: 'Drugs',
                update_data: {
                    is_delete: 1
                },
                condition: {
                    id
                }
            };
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                api.createBatchData(body).then(res => {
                    if(res.data.code === 200){
                        if(res.data.code === 200){
                            this.submitLoading = false;
                            this.boxSwitch = false;
                            this.$message({
                                message: '恭喜你，删除成功',
                                type: 'success'
                            });
                            this.getData()
                        }else {
                            this.$message.error(res.data.msg);
                        }
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
                
        },

        //-----上传图片相关-----
        //删除上传的图片
        clearImg(){
            this.form.image = '';
        },
        //上传图片
        addImgEvent(val){ 
            this.form.image = val;
        },
    },
}
</script>

<style lang="scss">
    .herb_list{
        .el-header{
            padding: 0;
        }
        .el-date-editor .el-range-separator{
            width: 20px;
        }
        .el-table__header tr th{
            background-color: #f6f6f6;
        }
        .content{
            padding: 20px 80px;
            overflow: hidden;
            .add_btn{
                margin-top: 20px;
            }
            .table_box{
                margin-top: 20px;
                .herb_img{
                    width: 100px;
                    max-width: 100px;
                    margin: auto;
                }
            }
            .pagination_box{
                padding: 4px;
                display: flex;
                justify-content: space-between;
                background-color: #f6f6f6;
                border: 1px solid #eee;
                border-top: none;
                .checkedAll{
                    line-height: 40px;
                    margin-left: 6px;
                }
            }
            .update-img {
                margin-left: 0;
            }
            .update-img .img-box .clear-icon{
                width: 20px;
                height: 20px;
                font-size: 16px;
                line-height: 20px;
                text-align: center;
                cursor: pointer;
            }
        }
    }
</style>
